metadata name = 'SQL Managed Instance Vulnerability Assessments'
metadata description = 'This module deploys a SQL Managed Instance Vulnerability Assessment.'

@description('Required. The name of the vulnerability assessment.')
param name string

@description('Conditional. The name of the parent SQL managed instance. Required if the template is used in a standalone deployment.')
param managedInstanceName string

@description('Optional. The recurring scans configuration.')
param recurringScans resourceInput<'Microsoft.Sql/managedInstances/vulnerabilityAssessments@2023-08-01'>.properties.recurringScans?

@description('Required. A blob storage to hold the scan results.')
param storageAccountResourceId string

@description('Optional. Use Access Key to access the storage account. The storage account cannot be behind a firewall or virtual network. If an access key is not used, the SQL MI system assigned managed identity must be assigned the Storage Blob Data Contributor role on the storage account.')
param useStorageAccountAccessKey bool = false

@description('Optional. Create the Storage Blob Data Contributor role assignment on the storage account. Note, the role assignment must not already exist on the storage account.')
param createStorageRoleAssignment bool = true

resource managedInstance 'Microsoft.Sql/managedInstances@2024-05-01-preview' existing = {
  name: managedInstanceName
}

resource storageAccount 'Microsoft.Storage/storageAccounts@2025-01-01' existing = {
  name: last(split(storageAccountResourceId, '/'))
  scope: resourceGroup(split(storageAccountResourceId, '/')[2], split(storageAccountResourceId, '/')[4])
}

// Assign SQL MI MSI access to storage account
module storageAccount_sbdc_rbac 'modules/nested_storageRoleAssignment.bicep' = if (!useStorageAccountAccessKey && createStorageRoleAssignment) {
  name: '${managedInstance.name}-sbdc-rbac'
  scope: resourceGroup(split(storageAccountResourceId, '/')[4])
  params: {
    storageAccountName: last(split(storageAccountResourceId, '/'))
    managedInstanceIdentityPrincipalId: managedInstance.identity.principalId
  }
}

resource vulnerabilityAssessment 'Microsoft.Sql/managedInstances/vulnerabilityAssessments@2024-05-01-preview' = {
  name: name
  parent: managedInstance
  properties: {
    storageContainerPath: 'https://${last(split(storageAccountResourceId, '/'))}.blob.${environment().suffixes.storage}/vulnerability-assessment/'
    storageAccountAccessKey: useStorageAccountAccessKey ? storageAccount.listKeys().keys[0].value : null
    recurringScans: recurringScans
  }
}

@description('The name of the deployed vulnerability assessment.')
output name string = vulnerabilityAssessment.name

@description('The resource ID of the deployed vulnerability assessment.')
output resourceId string = vulnerabilityAssessment.id

@description('The resource group of the deployed vulnerability assessment.')
output resourceGroupName string = resourceGroup().name
